#include <string>
#include<thread>
#include<iostream>

// 方式1，使用局部静态变量, 懒汉式
class Singleton2{
private:
    std::string value_;
    Singleton2(const std::string value): value_(value) {}
    Singleton2(const Singleton2&) = delete;
    Singleton2 &operator=(const Singleton2&) = delete;
public:
    static Singleton2& GetInstance(const std::string& value = ""){
        static Singleton2 instance(value);
        return instance;
    }

    std::string value() const { return value_; }
};

void ThreadFoo(){
    std::this_thread::sleep_for(std::chrono::microseconds(1000));
    Singleton2& singleton = Singleton2::GetInstance("FOo");
    std::cout << singleton.value() << "\n";
}

void ThreadBar(){
    std::this_thread::sleep_for(std::chrono::microseconds(1000));
    Singleton2& singleton = Singleton2::GetInstance("Bar");
    std::cout << singleton.value() << "\n";
}

int main(){
    std::cout<<"如果看到相同的值，说明单例被重用了 (正确!)\n" <<
                "如果看到不同的值，说明创建了2个单例 (错误!)\n\n" <<
                "运行结果:\n"; 
    std::thread t1(ThreadBar);
    std::thread t2(ThreadFoo);
    t1.join();
    t2.join();
    return 0;
}